package main

import (
	"log"
	"strings"
	"time"

	"bankend/config"
	"bankend/controllers"
	"bankend/database"
	"bankend/middleware"
	"bankend/services"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func main() {
	// 1. 加载配置
	config.LoadConfig()

	// 2. 初始化数据库连接
	database.InitDB()

	// 3. 启动 Gin 引擎
	router := gin.New()

	if err := router.SetTrustedProxies([]string{
		"127.0.0.1", // 本地开发回环
		"::1",       // IPv6 回环
		// 生产环境请填写反向代理 IP 或网段
	}); err != nil {
		log.Fatalf("设置可信代理失败: %v", err)
	}

	// 4. 中间件：日志、恢复、CORS、JWT
	router.Use(gin.Logger(), gin.Recovery())
	router.Use(cors.New(cors.Config{
		AllowOriginFunc: func(origin string) bool {
			return strings.HasPrefix(origin, "http://localhost:5173")
		},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
		MaxAge:           12 * time.Hour,
	}))
	router.Use(middleware.JWTAuthMiddleware()) // 添加JWT中间件

	// 5. 后台协程：延迟预热 access_token 并定时刷新
	go func() {
		// 等待反向代理生效
		time.Sleep(5 * time.Second)

		// 首次预热
		if token, err := services.GetAccessToken(); err != nil {
			log.Println("预热 access_token 失败：", err)
		} else {
			log.Println("首次预热 access_token：", token)
		}

		// 定时刷新（微信 token 有效期 2h，这里用 90 分钟）
		ticker := time.NewTicker(90 * time.Minute)
		defer ticker.Stop()
		for range ticker.C {
			if token, err := services.GetAccessToken(); err != nil {
				log.Println("定时刷新 access_token 失败：", err)
			} else {
				log.Println("定时刷新 access_token：", token)
			}
		}
	}()

	// 6. 路由定义
	api := router.Group("/api")
	{
		// 用户管理
		api.GET("/users", controllers.GetUsersFuzzy)
		api.GET("/users/:id", controllers.GetUser)
		api.POST("/users", controllers.CreateUser)
		api.PUT("/users/:id", controllers.UpdateUser)
		api.DELETE("/users/:id", controllers.DeleteUser)

		// 用户订阅设置
		api.GET("/user-subscribes/:user_id", controllers.GetUserSubscribe)
		api.POST("/user-subscribes", controllers.CreateUserSubscribe)
		api.PUT("/user-subscribes/:user_id", controllers.UpdateUserSubscribe)
		api.DELETE("/user-subscribes/:user_id", controllers.DeleteUserSubscribe)

		// 推送目标选择
		api.GET("/push_audience", controllers.GetPushAudience)

		// 登录注册
		api.POST("/login", controllers.Login)
		api.POST("/register", controllers.Register)

		// 消息模板
		api.GET("/message_templates", controllers.GetMessageTemplates)
		api.GET("/message_templates/:id", controllers.GetMessageTemplate)
		api.POST("/message_templates", controllers.CreateMessageTemplate)
		api.PUT("/message_templates/:id", controllers.UpdateMessageTemplate)
		api.DELETE("/message_templates/:id", controllers.DeleteMessageTemplate)
		api.POST("/message_templates/push", controllers.PushMessageTemplate)

		// 自动回复规则
		api.GET("/auto_replies", controllers.GetAutoReplies)
		api.GET("/auto_replies/:id", controllers.GetAutoReply)
		api.POST("/auto_replies", controllers.CreateAutoReply)
		api.PUT("/auto_replies/:id", controllers.UpdateAutoReply)
		api.DELETE("/auto_replies/:id", controllers.DeleteAutoReply)
		api.POST("/auto_replies/process", controllers.ProcessAutoReply)
	}

	wx := router.Group("/wx")
	{
		// 微信接入 & 模板消息
		wx.GET("", controllers.WeChatToken)
		wx.GET("/getUserCode", controllers.GetUserCode)
		wx.GET("/getUserOpenId", controllers.GetUserOpenId)
		wx.GET("/getAccessToken", controllers.GetAccessToken)
		wx.POST("/order/notify", controllers.SendOrderNotification)
		wx.GET("/menu/get", controllers.GetMenuConfig)
		wx.POST("/menu/create", controllers.SaveMenuConfig)

		// 统一接收微信事件/消息推送
		wx.POST("", controllers.HandleWeChatEvent)
		
		// 群发消息
		wx.POST("/mass/sendall", controllers.SendMassMessage)
	}

	// 7. 启动服务器
	addr := ":" + config.AppConfig.Port
	log.Printf("服务器启动，监听端口 %s", config.AppConfig.Port)
	if err := router.Run(addr); err != nil {
		log.Fatalf("启动失败: %v", err)
	}
}
